/*
 * Copyright (c) 2017 Richard Palethorpe <rpalethorpe@suse.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
/*
 * CVE-2016-7117
 *
 * This tests for a use after free caused by a race between recvmmsg() and
 * close(). The exit path for recvmmsg() in (a2e2725541f: net: Introduce
 * recvmmsg socket syscall) called fput() on the active file descriptor before
 * checking the error state and setting the socket's error field.
 *
 * If one or more messages are received by recvmmsg() followed by one which
 * fails, the socket's error field will be set. If just after recvmmsg() calls
 * fput(), a call to close() is made on the same file descriptor there is a
 * race between close() releasing the socket object and recvmmsg() setting its
 * error field.
 *
 * fput() does not release a file descriptor's resources (e.g. a socket)
 * immediatly, it queues them to be released just before a system call returns
 * to user land. So the close() system call must call fput() after it is
 * called in recvmmsg(), exit and release the resources all before the socket
 * error is set.
 *
 * Usually if the vulnerability is present the test will be killed with a
 * kernel null pointer exception. However this is not guaranteed to happen
 * every time.
 *
 * The following was used for reference
 * https://blog.lizzie.io/notes-about-cve-2016-7117.html
 */

#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <stdlib.h>
#include <errno.h>

#include "tst_test.h"
#include "tst_safe_net.h"
#include "tst_safe_pthread.h"
#include "tst_timer.h"
#include "tst_fuzzy_sync.h"

/* The bug was present in the kernel before recvmmsg was exposed by glibc */
#include "lapi/syscalls.h"

#include "config.h"

#define MSG "abcdefghijklmnop"
#define RECV_TIMEOUT 1
#define ATTEMPTS 0x1FFFFF

#ifndef HAVE_STRUCT_MMSGHDR
struct mmsghdr {
	struct msghdr msg_hdr;
	unsigned int msg_len;
};
#endif

static volatile int socket_fds[2];
static struct mmsghdr msghdrs[2] = {
	{
		.msg_hdr = {
			.msg_iov = &(struct iovec) {
				.iov_len = sizeof(MSG),
			},
			.msg_iovlen = 1
		}
	},
	{
		.msg_hdr = {
			.msg_iov = &(struct iovec) {
				.iov_base = (void *)(0xbadadd),
				.iov_len = ~0,
			},
			.msg_iovlen = 1
		}
	}
};
static char rbuf[sizeof(MSG)];
static struct timespec timeout = { .tv_sec = RECV_TIMEOUT };
static struct tst_fzsync_pair fzsync_pair = TST_FZSYNC_PAIR_INIT;
static pthread_t pt_send;
static void *send_and_close(void *);

static void setup(void)
{
	SAFE_PTHREAD_CREATE(&pt_send, 0, send_and_close, 0);
}

static void cleanup(void)
{
	close(socket_fds[0]);
	close(socket_fds[1]);

	if (pt_send) {
		tst_fzsync_pair_exit(&fzsync_pair);
		SAFE_PTHREAD_JOIN(pt_send, 0);
	}
}

static void *send_and_close(void *arg)
{
	while (tst_fzsync_wait_update_b(&fzsync_pair)) {
		send(socket_fds[0], MSG, sizeof(MSG), 0);
		send(socket_fds[0], MSG, sizeof(MSG), 0);

		tst_fzsync_delay_b(&fzsync_pair);

		close(socket_fds[0]);
		close(socket_fds[1]);
		tst_fzsync_time_b(&fzsync_pair);
		if (!tst_fzsync_wait_b(&fzsync_pair))
			break;
	}
	return arg;
}

static void run(void)
{
	int i, stat, too_early_count = 0;

	msghdrs[0].msg_hdr.msg_iov->iov_base = (void *)&rbuf;

	for (i = 1; i < ATTEMPTS; i++) {
		if (socketpair(AF_LOCAL, SOCK_DGRAM, 0, (int *)socket_fds))
			tst_brk(TBROK | TERRNO, "Socket creation failed");

		tst_fzsync_wait_update_a(&fzsync_pair);
		tst_fzsync_delay_a(&fzsync_pair);

		stat = tst_syscall(__NR_recvmmsg,
				   socket_fds[1], msghdrs, 2, 0, &timeout);
		tst_fzsync_time_a(&fzsync_pair);
		if (stat < 0 && errno == EBADF)
			too_early_count++;
		else if (stat == 0)
			tst_res(TWARN, "No messages received, should be one");
		else if (stat < 0)
			tst_res(TWARN | TERRNO, "recvmmsg failed unexpectedly");

		tst_fzsync_wait_a(&fzsync_pair);
	}

	tst_res(TPASS, "Nothing happened after %d attempts", ATTEMPTS);
}

static struct tst_test test = {
	.setup = setup,
	.test_all = run,
	.cleanup = cleanup,
	.min_kver = "2.6.33",
};
